<template>
	<musichead class="musichead" name="摸摸鱼" :isShowback="true" />
	<view class="play-everyone">
		<view class="play-box">
			<view class="play-img" :class="{'rotate': isPlaying}">
				<image :src="currentSong?.imgurl || '../../static/logo.png'" mode="aspectFill" />
			</view>
			<view class="sing-word">
				<view class="lyric-wrapper" ref="lyricWrapper">
					<view class="lyric-container" ref="lyricContainer" :style="{ transform: `translateY(${-currentLine * lineHeight}px)` }">
						<view class="lyric-line" :class="{ 'active': index === currentLine }"
							v-for="(line, index) in lyrics" :key="index">
							{{ line.text }}
						</view>
					</view>
				</view>
			</view>
			<view class="play-time">
				<text class="current-time">{{formatTime(currentTime)}}</text>
				<text class="divider">/</text>
				<text class="total-time">{{formatTime(duration)}}</text>
			</view>
			<view class="play-btn">
				<text class="iconfont icon-prev" @click="handlePrev"></text>
				<text v-if="!isPlaying" class="iconfont icon-zanting2" @click="handlePlay"></text>
				<text v-if="isPlaying" class="iconfont icon-zanting1" @click="handlePause"></text>
				<text class="iconfont icon-xiayiqu" @click="handleNext"></text>
			</view>
		</view>
	</view>
</template>

<script>
	import musichead from '../../components/musichead/musichead.vue'
	import {
		getSongWordUrl
	} from '../../common/api.js'
	import audioManager from '@/common/audioManager.js'

	export default {
		name: 'Play',
		components: {
			musichead
		},
		props: {
			songInfo: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				lyrics: [], // 歌词数组，每项包含 time 和 text
				currentLine: 0,
				offset: 0,
				lineHeight: 40,
				currentTime: 0,
				duration: 0,
				isPlaying: true,
				currentSong: null
			}
		},
		watch: {
			currentTime(newTime) {
				this.updateLyricLine(newTime);
			}
		},
		mounted() {
			// 延迟获取行高，确保DOM已经渲染
			this.$nextTick(() => {
				setTimeout(() => {
					const container = this.$refs.lyricContainer;
					if (container && container.children && container.children.length > 0) {
						this.lineHeight = container.children[0].offsetHeight || 40;
					}
				}, 100);
			});
		},
		methods: {
			// 格式化时间
			formatTime(time) {
				time = Math.floor(time || 0);
				const minutes = Math.floor(time / 60);
				const seconds = time % 60;
				return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
			},

			// 解析歌词
			parseLyric(lrc) {
				const lines = lrc.split('\n');
				const lyrics = [];
				
				lines.forEach(line => {
					const matchResult = line.match(/\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/);
					if (matchResult) {
						const minutes = parseInt(matchResult[1]);
						const seconds = parseInt(matchResult[2]);
						const milliseconds = parseInt(matchResult[3]);
						const text = matchResult[4].trim();
						
						if (text && !text.includes('作词') && !text.includes('作曲') && !text.includes('编曲')) {
							const time = minutes * 60 + seconds + milliseconds / 1000;
							lyrics.push({
								time,
								text
							});
						}
					}
				});
				
				return lyrics.sort((a, b) => a.time - b.time);
			},

			// 更新当前歌词行
			updateLyricLine(currentTime) {
				if (!this.lyrics || this.lyrics.length === 0) return;
				
				let targetLine = 0;
				for (let i = 0; i < this.lyrics.length; i++) {
					if (currentTime >= this.lyrics[i].time) {
						targetLine = i;
					} else {
						break;
					}
				}
				
				if (this.currentLine !== targetLine) {
					this.currentLine = targetLine;
					this.updateOffset();
				}
			},

			// 更新歌词滚动偏移
			updateOffset() {
				const wrapper = this.$refs.lyricWrapper;
				const container = this.$refs.lyricContainer;
				if (!wrapper || !container) return;

				const wrapperHeight = wrapper.clientHeight;
				const lineHeight = 42; // 行高(32) + 内边距(5*2)
				const paddingTop = 60; // 与 CSS 中的 padding 对应

				// 计算当前行在容器中的位置
				const currentLineTop = this.currentLine * lineHeight + paddingTop;
				
				// 目标偏移量：当前行位置 - 容器高度的1/3位置
				const targetOffset = -(currentLineTop - wrapperHeight / 3);
				
				// 限制偏移范围
				const minOffset = -(container.clientHeight - wrapperHeight);
				this.offset = Math.max(minOffset, Math.min(0, targetOffset));
			},

			// 播放控制方法
			handlePlay() {
				audioManager.play();
			},
			
			handlePause() {
				audioManager.pause();
			},
			
			handlePrev() {
				audioManager.playPrev();
			},
			
			handleNext() {
				audioManager.playNext();
			},

			// 初始化音频管理器事件监听
			initAudioEvents() {
				// 监听播放时间更新
				audioManager.onTimeUpdate(time => {
					this.currentTime = time;
				});

				// 监听播放状态变化
				audioManager.onPlayStatusChange(status => {
					this.isPlaying = status.isPlaying;
				});

				// 监听歌曲变化
				audioManager.onSongChange(song => {
					this.currentSong = song.current;
					this.duration = song.current?.Time || 0;
					// 歌曲切换时重新获取歌词
					this.fetchLyrics();
				});
			},

			// 获取歌词
			async fetchLyrics() {
				if (!this.currentSong?.id) return;
				
				try {
					const songword = await getSongWordUrl(this.currentSong.id);
					if (songword) {
						this.lyrics = this.parseLyric(songword);
						// 立即更新当前歌词行
						this.updateLyricLine(this.currentTime);
					}
				} catch (error) {
					console.error('获取歌词失败:', error);
					this.lyrics = [{ time: 0, text: '暂无歌词' }];
				}
			},

			// 初始化页面数据
			async initPageData() {
				// 如果有传入的 songInfo，优先使用
				if (this.songInfo) {
					try {
						const songData = JSON.parse(decodeURIComponent(this.songInfo));
						this.currentSong = songData.current;
						this.duration = songData.current?.Time || 0;
					} catch (error) {
						console.error('解析 songInfo 失败:', error);
					}
				}

				if (!this.currentSong) {
					// 获取当前播放状态
					const playStatus = audioManager.getPlayStatus();
					this.isPlaying = playStatus.isPlaying;
					this.currentTime = playStatus.currentTime;

					// 获取当前歌曲信息
					const songData = audioManager.getCurrentSong();
					this.currentSong = songData.current;
					this.duration = songData.current?.Time || 0;
				}

				// 获取歌词
				await this.fetchLyrics();
			}
		},
		async onLoad(options) {
			// 初始化页面数据
			await this.initPageData();
			// 初始化音频事件监听
			this.initAudioEvents();
		},
		onUnload() {
			// 移除音频事件监听
			audioManager.offTimeUpdate();
			audioManager.offPlayStatusChange();
			audioManager.offSongChange();
		}
	}
</script>

<style lang="scss">
	.musichead {
		position: absolute;
		width: 100vw;
	}

	.play-everyone {
		width: 100vw;
		height: 100vh;
		background-color: #404040;
		//background: url('../../static/imgs/q.png');
		background-size: cover;
		background-repeat: no-repeat;
		display: flex;
		align-items: center;
		justify-content: center;

		.play-box {
			width: 100vw;
			height: 75%;

			.play-img {
				width: 120px;
				height: 120px;
				border-radius: 50%;
				margin: auto;
				margin-top: 20%;
				margin-bottom: 10%;
				overflow: hidden;
				box-shadow: 0px 4px 10px 5px rgba(0, 0, 0, 0.4);
				
				&.rotate {
					animation: rotate 8s linear infinite;
				}
				
				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}

			@keyframes rotate {
				from { transform: rotate(0deg); }
				to { transform: rotate(360deg); }
			}

			.sing-word {
				width: 100%;
				height: 40%;
				position: relative;
				overflow: hidden;

				.lyric-wrapper {
					width: 100%;
					height: 100%;
					overflow-y: auto;
					mask-image: linear-gradient(
						180deg,
						transparent 0%,
						rgba(0, 0, 0, 1) 20%,
						rgba(0, 0, 0, 1) 80%,
						transparent 100%
					);
					-webkit-mask-image: linear-gradient(
						180deg,
						transparent 0%,
						rgba(0, 0, 0, 1) 20%,
						rgba(0, 0, 0, 1) 80%,
						transparent 100%
					);

					.lyric-container {
						width: 100%;
						transition: transform 0.6s cubic-bezier(0.16, 1, 0.3, 1);
						padding: 60px 0;

						.lyric-line {
							width: 100%;
							min-height: 32px;
							line-height: 32px;
							text-align: center;
							color: rgba(255, 255, 255, 0.6);
							font-size: 14px;
							transition: all 0.3s ease;
							padding: 5px 0;

							&.active {
								color: rgb(126, 209, 121);
								font-size: 20px;
								font-weight: 600;
								transform: scale(1.2);
							}
						}
					}
				}
			}

			.play-time {
				width: 100%;
				height: 30px;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 10px 0;

				.current-time, .total-time, .divider {
					font-size: 14px;
					color: rgba(255, 255, 255, 0.8);
				}

				.divider {
					margin: 0 5px;
				}
			}

			.play-btn {
				width: 100%;
				height: 20%;
				display: flex;
				align-items: center;
				justify-content: center;

				text {
					font-size: 50px;
					color: #fefefe;
					// background: linear-gradient(to bottom, rgba(255, 255, 255, 0), #fff); 
					// box-shadow: 20px 10px 10px rgba(71, 255, 249, 0.1);
					box-shadow: 0 5px 25px rgba(202, 202, 202, 0.2);
					background-color: rgba(255, 255, 255, 0.2); 
					-webkit-backdrop-filter: blur(8px);
					backdrop-filter: blur(8px);
					margin: 0 20px;
					opacity: 0.8;
					
					&:active {
						opacity: 0.6;
					}
				}
			}
		}
	}
</style>
